package Orm.jdbc.ormdiy;

import Orm.jdbc.connectorPool.JDBCUtils;
import java.sql.*;

public class WaterRepositoryImp {

    /**
     * 通用insert update delete方法
     * @param sql 预执行需要SQL
     * @param args 根据SQL中? 准备参数
     */
    public static void update(String sql, Object... args) throws SQLException {
        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            conn = JDBCUtils.getConnection();
            stmt = conn.prepareStatement(sql);
            // 设置参数 --- 根据？设置参数
            ParameterMetaData parameterMetaData = stmt.getParameterMetaData();
            int count = parameterMetaData.getParameterCount();
            for (int i = 1; i <= count; i++) {
                stmt.setObject(i, args[i - 1]);
            }
            stmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            stmt.close();
            conn.close();
        }
    }

    /**
     * 通用select方法
     */
    public static <R> R query(String sql, Class<?> clazz ,Object... args) throws SQLException {
        ResultHandler<R> handler = new DefaultResultHandler<>();
        R obj = null;
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtils.getConnection();
            assert conn != null;
            stmt = conn.prepareStatement(sql);
            // 设置参数
            ParameterMetaData parameterMetaData = stmt.getParameterMetaData();
            int count = parameterMetaData.getParameterCount();
            for (int i = 1; i <= count; i++) {
                stmt.setObject(i, args[i - 1]);
            }
            rs = stmt.executeQuery();
            obj = handler.handle(rs,clazz);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            rs.close();
            stmt.close();
            conn.close();
        }
        return obj;
    }


}
